# !/usr/bin/env python
# _*_ coding:utf-8 _*_
import os

from django.conf import settings

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories


# 1.交互数据库
def generate_static_index_html():
    print("每隔一分钟 生成一个index.html")
    # 1.三级商品分类获取 14句
    categories = get_categories()

    # 2. 广告数据的获取 4句
    # 2.1.获取 所有 广告分类
    ad_categories = ContentCategory.objects.all()
    # 2.2 遍历
    contents = {}
    for ad in ad_categories:
        # 2.3 组合前端需要的数据格式---分类--广告内容 content_set.filter()
        contents[ad.key] = ad.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': categories,
        'contents': contents
    }

    # 2.获取模板文件
    from django.template import loader
    template = loader.get_template('index.html')

    # 3. 拼接渲染--->string
    html_text = template.render(context)

    # 4.写入文件
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w') as f:
        f.write(html_text)
